<template lang="html">

    <div class="editable-cell">
        <input type="text" v-model="inputValue" :readonly="!editable"
            v-focus="focusOrNot" @keypress="filterInvalidChars"
            @click="focusInput" @blur="blurInput">
        <div class="edit-icon" @click="focusInput" v-show="editable">
            <i class="iconfont icon-editor"></i>
        </div>
    </div>

</template>

<script>

import Bus from '@/utils/event_bus'

export default {

    directives: {
        focus: {
            inserted: function (el, bindings) {
                if (bindings.value) {
                    el.focus();
                } else {
                    el.blur();
                }
            },
            update: function(el, bindings) {
                if (bindings.value) {
                    el.focus();
                } else {
                    el.blur();
                }
            },
            componentUpdated: function(el, bindings) {
                if (bindings.value) {
                    el.focus();
                } else {
                    el.blur();
                }
            }
        }
    },

    props: {

        cellValue: String,
        dataKey: String,
        dataIndex: null,
        editable: Boolean

    },

    data() {
        return {
            inputValue: this.cellValue,
            focusOrNot: false,
            showEditIcon: false
        };
    },

    created() {

        this.inputValue = this.cellValue;

    },

    methods: {
        focusInput() {
            this.focusOrNot = true;
        },

        blurInput() {
            this.focusOrNot = false;
        },

        filterInvalidChars() {
            return true;
        }
    },

    watch: {
        inputValue() {
            Bus.$emit('editable-cell-value-change', this.dataKey, this.inputValue, this.dataIndex);
        }
    }

}
</script>

<style lang="scss" scoped>

@import "common";

.editable-cell {

    font-size: 12px;

    &:hover .edit-icon {
        color: #4db3ff;
    }

    input {
        color: rgba(0, 0, 0, 0.65);
        padding: 3px 8px;
        width: calc(100% - 19px);
        font-size: 12px;

        &:focus {
            // border: 1px solid #ccc;
            // border-radius: 2px;
            background: #fff;
        }

    }

    .edit-icon {

        display: inline-block;
        cursor: pointer;
        color: #ccc;

        >i {
            font-size: 12px;
        }
    }

}

</style>
